这个头文件提供 线程 相关的功能。例如线程控制、互斥量、条件变量、线程局部存储等。
宏 | 标准 | 说明 |
---|
TSS_DTOR_ITERATIONS | C11 | 线程局部存储指针析构函数被 thrd_exit 调用的最大次数 |
线程状态枚举 | 标准 | 说明 |
---|
thrd_success | C11 | 表示成功 |
thrd_nomem | C11 | 表示内存不足 |
thrd_timedout | C11 | 表示超时 |
thrd_busy | C11 | 表示资源不可用 |
thrd_error | C11 | 表示错误 |
互斥量类型枚举 | 标准 | 说明 |
---|
mtx_plain | C11 | 普通互斥量 |
mtx_recursive | C11 | 递归互斥量 |
mtx_timed | C11 | 定时互斥量 |
类型 | 标准 | 说明 |
---|
thrd_t | C11 | 线程 ID |
mtx_t | C11 | 互斥量 ID |
cnd_t | C11 | 条件变量 ID |
tss_t | C11 | 线程局部存储指针 ID |
thrd_start_t | C11 | 线程启动函数的类型(int(*)(void*) ) |
tss_dtor_t | C11 | 线程局部存储指针析构函数的类型(void(*)(void*) ) |
#include <stdio.h>
#include <threads.h>
#include <stdlib.h>
int simple_thread(void *arg) {
int *id = (int*)arg;
printf("线程 %d 正在运行\n", *id);
return 0;
}
mtx_t mutex;
int shared_counter = 0;
int counter_thread(void *arg) {
int *iterations = (int*)arg;
for (int i = 0; i < *iterations; ++i) {
mtx_lock(&mutex);
shared_counter++;
mtx_unlock(&mutex);
}
return 0;
}
cnd_t condition;
mtx_t condition_mutex;
int data_ready = 0;
int producer_thread(void *arg) {
int *value = (int*)arg;
mtx_lock(&condition_mutex);
printf("生产者: 生成数据 %d\n", *value);
data_ready = 1;
cnd_signal(&condition);
mtx_unlock(&condition_mutex);
return 0;
}
int consumer_thread(void *arg) {
(void)arg;
mtx_lock(&condition_mutex);
while (!data_ready) {
printf("消费者: 等待数据...\n");
cnd_wait(&condition, &condition_mutex);
}
printf("消费者: 接收到数据\n");
mtx_unlock(&condition_mutex);
return 0;
}
int main(void) {
thrd_t threads[3];
int ids[3] = {1, 2, 3};
printf("=== 简单线程示例 ===\n");
for (int i = 0; i < 3; i++) {
thrd_create(&threads[i], simple_thread, &ids[i]);
}
for (int i = 0; i < 3; i++) {
thrd_join(threads[i], NULL);
}
printf("\n=== 互斥锁示例 ===\n");
mtx_init(&mutex, mtx_plain);
int iterations = 100000;
thrd_t t1, t2;
thrd_create(&t1, counter_thread, &iterations);
thrd_create(&t2, counter_thread, &iterations);
thrd_join(t1, NULL);
thrd_join(t2, NULL);
printf("最终计数器值: %d (应为: %d)\n", shared_counter, 2 * iterations);
mtx_destroy(&mutex);
printf("\n=== 条件变量示例 ===\n");
mtx_init(&condition_mutex, mtx_plain);
cnd_init(&condition);
int value = 42;
thrd_t producer, consumer;
thrd_create(&consumer, consumer_thread, NULL);
thrd_sleep(&(struct timespec){.tv_sec=1}, NULL);
thrd_create(&producer, producer_thread, &value);
thrd_join(producer, NULL);
thrd_join(consumer, NULL);
mtx_destroy(&condition_mutex);
cnd_destroy(&condition);
return 0;
}
运行结果:
=== 简单线程示例 ===
线程 1 正在运行
线程 2 正在运行
线程 3 正在运行
=== 互斥锁示例 ===
最终计数器值: 200000 (应为: 200000)
=== 条件变量示例 ===
消费者: 等待数据...
生产者: 生成数据 42
消费者: 接收到数据